<?php
class Search_model extends CI_Model{
	
	function __construct(){
		parent::__construct();
		$this->load->database();
	}
	
	/**
	 * 	BUSCADOR DE PELICULAS, SERIES Y ACTORES
	 * 
	 * 	@param array $params			Parametros Post enviados
	 * 
	 * 	@return Array
	 */
	public function search($params){
		$limit = isset($params['limit'])? $params['limit']: 10;
		$filter_text = $params['filter_text'];	
		$is_one = (count(explode(" ", $params['filter_text']))>1) ? FALSE : TRUE ;
		$str_match = ($is_one) ? '' : ", MATCH(titulo) AGAINST('$filter_text') AS coincidencia";
		
		$this->db->
					select("titulo AS title, url_web, tabla, id_tabla".$str_match)->from('buscador');
					
						if($is_one){
							$this->db->like('titulo', $params['filter_text']);
							$this->db->order_by('titulo ASC');
						}
						else{
							$this->db->where("MATCH(titulo) AGAINST ('$filter_text')", NULL , FALSE);
							$this->db->order_by('coincidencia DESC');
						}
		$this->db->limit($limit);
		
		$res	= $this->db->get();
		foreach ($res->result_array() as $key => $value) {
			$value['image'] = $this->{'getImg_'.$value['tabla']}($value['id_tabla']);
			unset($value['id_tabla'], $value['tabla']);
			$array['result_search'][] = $value;
		}
		
		return array($array);
		
	}
	
	
	private function getImg_peliculas($id){
		$res = $this->db
			->select('url_poster_small')
			->from('peliculas')
			->where('id_pelicula = '.$id)
		->get();
		$res = $res->row();
		return $res->url_poster_small;
	}
	private function getImg_series_capitulos($id){
		$res = $this->db
			->select('st.url_poster_small')
			->from('series_temporadas AS st')
			->join('series_capitulos AS sc', 'st.id_temporada = sc.id_temporada', 'inner')
			->where('sc.id_capitulo = '.$id)
		->get();
		$res = $res->row();
		return $res->url_poster_small;
	}
	private function getImg_series_temporadas($id){
		$res = $this->db
			->select('url_poster_small')
			->from('series_temporadas')
			->where('id_temporada = '.$id)
		->get();
		$res = $res->row();
		return $res->url_poster_small;
	}
	private function getImg_actores($id){
		return Sys::$url_base.'application/images/anonimous44.jpg';
	}
}